<script setup lang="ts">
import { computed, ref, watch } from 'vue'
const food = ref('猪脚饭')
const drink = ref('凉茶')
const foodObj = ref({
  name: '沙县小吃',
  price: 20,
  drink: {
    name: '可乐',
    price: 3,
  },
})

// 侦听器 watch
// 1.侦听单个响应式数据
watch(food, () => {
  console.log('侦听单个变量逻辑生效')
})
// 2. 侦听多个响应式数据
watch([food, drink], () => {
  console.log('侦听多个变量逻辑生效')
})
// 3. 侦听对象简单属性
watch(
  () => foodObj.value.price,
  () => {
    console.log('侦听简单对象逻辑生效')
  },
)
// 4. 侦听对象深层属性
watch(
  () => foodObj.value.drink,
  () => {
    console.log('侦听嵌套对象逻辑生效')
  },
  { deep: true },
)
// 5. 是否默认执行一次
watch(
  () => foodObj.value.drink,
  () => {
    console.log('侦听默认启动一次生效')
  },
  { immediate: true },
)
</script>

<template>
  <h2 @click="food += '!'">{{ food }}</h2>
  <h2 @click="drink += '!'">{{ drink }}</h2>
  <h1>{{ foodObj }}</h1>
  <button @click="foodObj.name += '~'">修改沙县小吃名字</button>
  <button @click="foodObj.price++">修改沙县小吃价格</button>
  <button @click="foodObj.drink.name += '~'">修改饮料名字</button>
  <button @click="foodObj.drink.price++">修改饮料价格</button>
</template>

<style></style>
